package data

import (
    "fmt"
    "time"
)

type User struct {
    Id       int `db:"id"`
    Uuid     string `db:"uuid"`
    Name     string `db:"name"`
    Email    string `db:"email"`
    Password string `db:"password"`
    CreatedAt int `db:"created_at"`
}
type Session struct {
    Id        int    `db:"id"`
    Uuid      string `db:"uuid"`
    Email     string `db:"email"`
    UserId    int    `db:"user_id"`
    CreatedAt int64  `db:"created_at"`
}

// Create a new session for an existing user 创建session
func (user *User) CreateSession() (session Session, err error) {

    res, err := Db.Exec("INSERT INTO  `session` (`uuid`, `email`, `user_id`, `created_at`) VALUES (?,?,?,?)", createUUID(), user.Email, user.Id, time.Now().Unix())

    if err != nil {
        fmt.Println("Create a new session error")
        return
    }
    id, err := res.LastInsertId()
    fmt.Println("id", id)
    err = Db.Get(&session, "SELECT id,uuid,email,user_id,created_at FROM session WHERE id=?", id)
    if err != nil {
        fmt.Println(err)
    }
    // fmt.Printf("11111%#v, ", session, id, "------")

    return
}

// Create a new user , save user info into DBMS
func (user *User) Create() (err error) {
    db := Db
    defer db.Close()
    r, err := db.Exec("INSERT INTO  `user` (`uuid`, `name`, `email`,`password`, `created_at`) VALUES (?,?,  ?, ?,?)",
        createUUID(), user.Name, user.Email, Encrypt(user.Password), time.Now().Unix())

    if err != nil {
        fmt.Println("exec failed,", err)

        return
    }
    _, err = r.LastInsertId()
    if err != nil {
        fmt.Println("exec failed,", err)
        return
    }
    // fmt.Println("insert succ:", id)
    return
}

// Get a single user given the email
func UserByEmail(email string) (user User, err error) {
    user = User{}
    err = Db.QueryRow("SELECT id, uuid, name, email, password, created_at FROM user WHERE email = ?", email).Scan(
        &user.Id, &user.Uuid, &user.Name, &user.Email, &user.Password, &user.CreatedAt)
    return
}

// check if session is valid in the dbms 检查是否存在session
func (session *Session) Check() (valid bool, err error) {
    err = Db.Ping()
    err = Db.Get(session, "SELECT id, uuid, email, user_id, created_at FROM session WHERE uuid =?", session.Uuid)
    if err != nil {
        valid = false
        return
    }
    if session.Id != 0 {
        valid = true
    }
    return
}

// get the  user   from  the session
func (sess *Session) User() (user User, err error) {
    // user = User{}
    fmt.Println(sess)
    err = Db.Get(&user, "SELECT id,uuid,name,email ,created_at FROM user WHERE id=?", sess.UserId)
   // fmt.Println(user)
    return
}
